<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
// @ts-ignore
import { ReadClients, WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()

type RouteItem = {
  id: number | string
  processRouteName: string
  processRouteNumber: string
  status: boolean | number | string
  description?: string
  remarks?: string
}

const readClient = ReadClients[3]
const writeClient = WriteClients[3]

// 移除事件定义，改为路由跳转

const loading = ref(false)
const tableData = ref<RouteItem[]>([])
const pagination = reactive({ pageIndex:1, pageSize:10, total:0 })

const queryForm = reactive({
  keyword: '', // 路线名称/编号
  status: '' as '' | boolean,
})

async function fetchList(){
  loading.value = true
  try{
    const params: any = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
    }
    // 添加搜索条件
    if(queryForm.keyword) params.keyword = queryForm.keyword
    if(typeof queryForm.status === 'boolean') params.status = queryForm.status
    
    console.log('查询参数:', params)
    const res = await readClient.get('/productread/api/ProcessRoute/ProcessRoute', { params }).catch(()=>({ data:{ data:{ items:[], total:0 }}}))

    const payload = res?.data ?? {}
    const root = payload.data ?? payload
    // 兼容常见结构：{data:{data:[], total}} 或 {data:{items:[], total}} 或 {items:[], total}
    const itemsRaw = root.data ?? root.items ?? root.rows ?? root.list ?? []
    const totalRaw = root.total ?? root.totalCount ?? root.count ?? (Array.isArray(itemsRaw) ? itemsRaw.length : 0)

    const toBool = (v:any)=> v===true || v===1 || v==='true'

    tableData.value = (Array.isArray(itemsRaw)? itemsRaw : []).map((it:any)=>{
      const id = it.id ?? it.Id ?? it.ID
      const processRouteName = it.processRouteName ?? it.ProcessRouteName ?? it.name
      const processRouteNumber = it.processRouteNumber ?? it.ProcessRouteNumber ?? it.code
      // 移除前端状态过滤，直接显示后端返回的状态
      const status = it.status ?? it.activationStatus ?? it.Enable
      const description = it.description ?? it.Description
      const remarks = it.remarks ?? it.Remarks
      console.log('处理行数据:', { id, processRouteName, processRouteNumber, status, description, remarks })
      return { id, processRouteName, processRouteNumber, status, description, remarks } as RouteItem
    })
    pagination.total = totalRaw || 0
    console.debug('ProcessRoute list normalized:', { payload, root, total: pagination.total, items: tableData.value })
  }catch{
    ElMessage.error('获取工艺路线失败')
  }finally{
    loading.value = false
  }
}

function handleSearch(){ pagination.pageIndex=1; fetchList() }
function handleReset(){ queryForm.keyword=''; queryForm.status=''; pagination.pageIndex=1; fetchList() }
function handlePageChange(p:number){ pagination.pageIndex=p; fetchList() }
function handleSizeChange(s:number){ pagination.pageSize=s; pagination.pageIndex=1; fetchList() }

async function handleRemove(row: RouteItem){
  try{
    console.log('删除行数据:', row)
    console.log('删除ID:', row.id)
    await ElMessageBox.confirm(`确认删除【${row.processRouteName}】吗？`, '提示', { type:'warning' })
    // 根据图片，删除接口是GET，且路径是 /api/ProcessRoute/DeleteProcessRoute
    await writeClient.get('/api/ProcessRoute/DeleteProcessRoute', { params:{ Id: row.id } })
    ElMessage.success('删除成功')
    fetchList()
  }catch(err:any){
    // 区分用户取消和实际错误
    if (err === 'cancel' || err?.message === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      console.error('删除失败:', err)
      ElMessage.error('删除失败')
    }
  }
}

function handleEdit(row: RouteItem){ 
  router.push({ name: 'ProcessRouteEdit', query: { id: row.id, origin: 'list' } })
}
function handleCreate(){ 
  router.push({ name: 'ProcessRouteCreate' })
}
function handleDetail(row: RouteItem){ 
  router.push({ name: 'ProcessRouteDetail', query: { id: row.id } })
}
function handleImport(){ ElMessage.info('导入：待对接接口'); }
function handleExport(){
  try{
    const url = `${readClient.defaults.baseURL}/api/ProcessRoute/Export`
    window.location.href = url
    ElMessage.success('导出任务已发起')
  }catch{ ElMessage.error('导出失败') }
}

onMounted(fetchList)
</script>

<template>
  <div class="process-page">
    <el-card class="toolbar">
      <div class="toolbar-row main">
        <div class="filters main">
          <el-input v-model="queryForm.keyword" placeholder="请输入工艺路线编号/名称" clearable class="flt" size="large" />
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable class="flt" size="large">
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </div>
        <div class="toolbar-actions">
          <el-button size="large" plain @click="handleReset">重置</el-button>
          <el-button size="large" type="primary" @click="handleSearch">查询</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <div class="title">工艺路线</div>
        </div>
      </template>
      <div class="action-bar">
        <el-button size="large" type="primary" @click="handleCreate">新增</el-button>
        <el-button size="large" @click="handleImport">导入</el-button>
        <el-button size="large" @click="handleExport">导出</el-button>
      </div>

      <el-table :data="tableData" v-loading="loading" class="compact-table">
        <el-table-column type="selection" width="48" />
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">{{ (pagination.pageIndex-1)*pagination.pageSize + scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="processRouteName" label="工艺路线名称" min-width="220">
          <template #default="scope">
            <el-link type="primary" underline="never" @click="handleDetail(scope.row)">{{ scope.row.processRouteName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="processRouteNumber" label="工艺路线编号" min-width="200" show-overflow-tooltip />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="(scope.row.status===true||scope.row.status===1)?'success':'info'">{{ (scope.row.status===true||scope.row.status===1)?'启用':'禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="工艺路线说明" min-width="220" show-overflow-tooltip />
        <el-table-column prop="remarks" label="备注" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="scope">
            <el-link type="primary" underline="never" @click="handleEdit(scope.row)">编辑</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" underline="never" @click="handleRemove(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          :page-sizes="[10,20,30,50]"
          :page-size="pagination.pageSize"
          :current-page="pagination.pageIndex"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.process-page{ display:flex; flex-direction:column; gap:12px; }
.toolbar{ padding-bottom:8px; }
.toolbar-row{ display:flex; align-items:center; justify-content:space-between; }
.filters.main{ display:flex; gap:12px; }
.flt{ width:280px; }
.toolbar-actions{ display:flex; gap:8px; }
.list-card :deep(.el-card__header){ padding:14px 16px; }
.list-header{ display:flex; align-items:center; justify-content:space-between; }
.list-header .title{ font-weight:600; }
.action-bar{ display:flex; gap:8px; padding-bottom:8px; }
.compact-table :deep(.el-table__cell){ padding:8px 0; }
.pagination{ display:flex; justify-content:flex-end; margin-top:12px; }
</style>

